package com.kzy.demoadmin.web.controller;

import com.github.pagehelper.PageInfo;
import com.kzy.demoadmin.web.config.AutoLog;
import com.kzy.demoadmin.web.entity.LoginParam;
import com.kzy.demoadmin.web.entity.Result;
import com.kzy.demoadmin.web.entity.User;
import com.kzy.demoadmin.web.entity.UserPageQuery;
import com.kzy.demoadmin.web.entity.VerifyCodeEntity;
import com.kzy.demoadmin.web.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 用户管理控制器
 * 处理用户登录、注册、查询、修改、删除等相关接口
 */
@Tag(name = "用户管理", description = "用户认证、信息管理相关接口（含登录、注册、CRUD操作）")
@RestController
@RequestMapping("/api/users")  // 补充统一接口前缀（与WebConfig配置一致）
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取验证码（用于登录/注册验证）
     */
    @Operation(summary = "获取验证码", description = "生成图形验证码，返回验证码图片Base64和验证码标识")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "验证码生成成功",
                    content = @Content(schema = @Schema(implementation = VerifyCodeEntity.class))),
            @ApiResponse(responseCode = "500", description = "验证码生成失败")
    })
    @GetMapping("/verify-code")
    public VerifyCodeEntity generateVerifyCode() throws IOException {
        return userService.generateVerifyCode();
    }

    /**
     * 用户登录
     * @param loginParam 登录参数（用户名、密码、验证码等）
     */
    @Operation(summary = "用户登录", description = "用户登录认证，成功返回用户信息和Token")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "登录成功",
                    content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "401", description = "用户名/密码错误或验证码失效"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @Parameters({
            @Parameter(name = "loginParam", description = "登录请求参数", required = true,
                    in = ParameterIn.DEFAULT, schema = @Schema(implementation = LoginParam.class))
    })
    @AutoLog(value = "该用户登录系统")
    @PostMapping("/login")
    public Result login(@RequestBody LoginParam loginParam) {
        User loginUser = userService.login(loginParam);
        return Result.success(loginUser);
    }

    /**
     * 注册用户/添加用户
     * @param user 用户信息（用户名、密码、昵称等）
     */
    @Operation(summary = "注册用户", description = "新用户注册，需传入完整用户信息（用户名需唯一）")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "注册成功"),
            @ApiResponse(responseCode = "400", description = "参数错误或用户名已存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @Parameters({
            @Parameter(name = "user", description = "用户注册信息", required = true,
                    in = ParameterIn.DEFAULT, schema = @Schema(implementation = User.class))
    })
    @PostMapping("/register")
    public Result add(@RequestBody User user) {
        userService.add(user);
        return Result.success();
    }

    /**
     * 分页查询（支持模糊查询）
     * @param query 分页查询参数（页码、每页条数、用户名模糊查询等）
     */
    @Operation(summary = "分页查询用户", description = "支持按用户名模糊查询，返回分页后的用户列表")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功",
                    content = @Content(schema = @Schema(implementation = PageInfo.class))),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @Parameters({
            @Parameter(name = "query", description = "分页查询参数", required = false,
                    in = ParameterIn.QUERY, schema = @Schema(implementation = UserPageQuery.class))
    })
    @GetMapping("/list")
    public Result getUserList(UserPageQuery query) {
        PageInfo<User> info = userService.getUserPage(query);
        return Result.success(info);
    }

    /**
     * 删除用户
     * @param id 用户ID
     */
    @Operation(summary = "删除用户", description = "根据用户ID删除指定用户（逻辑删除/物理删除，取决于服务层实现）")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "用户不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @Parameters({
            @Parameter(name = "id", description = "用户唯一标识ID", required = true,
                    in = ParameterIn.PATH, example = "1", schema = @Schema(type = "integer"))
    })
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.deleteById(id));
    }

    /**
     * 修改用户信息
     * @param user 修改后的用户信息（需包含用户ID）
     */
    @Operation(summary = "修改用户信息", description = "根据用户ID更新用户信息（用户名、昵称、状态等）")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "修改成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "用户不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @Parameters({
            @Parameter(name = "user", description = "修改后的用户信息（必须包含id）", required = true,
                    in = ParameterIn.DEFAULT, schema = @Schema(implementation = User.class))
    })
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.edit(user);
        return Result.success();
    }

    /**
     * 根据ID查询用户详情
     * @param id 用户ID
     */
    @Operation(summary = "根据ID查询用户", description = "根据用户唯一ID查询用户完整信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功",
                    content = @Content(schema = @Schema(implementation = User.class))),
            @ApiResponse(responseCode = "404", description = "用户不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @Parameters({
            @Parameter(name = "id", description = "用户唯一标识ID", required = true,
                    in = ParameterIn.PATH, example = "1", schema = @Schema(type = "integer"))
    })
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        return Result.success(userService.findById(id));
    }
}